from fastapi import APIRouter, HTTPException, Depends, File, UploadFile
from fastapi.responses import StreamingResponse
from models.database import get_db_connection
from models.schemas import ChatRequest, ChatResponse, MessageResponse, ChatHistorySave
from utils.auth import get_current_user
from config import settings
import mysql.connector
import logging
import uuid
from datetime import datetime

router = APIRouter(prefix="/chat", tags=["智能咨询"])

# 延迟初始化AI客户端
_ai_client = None


def get_ai_client():
    global _ai_client
    if _ai_client is None:
        from utils.llm_integration import ZhipuAIClient
        _ai_client = ZhipuAIClient(api_key=settings.ZHIPU_API_KEY)
        print("✅ AI客户端初始化成功")
    return _ai_client


def save_chat_message(user_id: int, session_id: str, role: str, message_type: str,
                      content: str, image_url: str = None, good_id: int = None):
    """保存聊天消息到数据库"""
    connection = get_db_connection()
    if not connection:
        logging.error("数据库连接失败，无法保存聊天记录")
        return

    try:
        cursor = connection.cursor()
        query = """
            INSERT INTO chat_history 
            (user_id, session_id, role, message_type, content, image_url, good_id)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """
        cursor.execute(query, (user_id, session_id, role, message_type, content, image_url, good_id))
        connection.commit()
    except mysql.connector.Error as e:
        logging.error(f"保存聊天记录失败: {e}")
        connection.rollback()
    finally:
        cursor.close()
        connection.close()


def get_or_create_session_id(user_id: int, provided_session_id: str = None) -> str:
    """获取或创建会话ID"""
    if provided_session_id:
        # 验证提供的会话ID是否属于该用户
        connection = get_db_connection()
        if connection:
            try:
                cursor = connection.cursor(dictionary=True)
                cursor.execute(
                    "SELECT session_id FROM chat_history WHERE user_id = %s AND session_id = %s LIMIT 1",
                    (user_id, provided_session_id)
                )
                if cursor.fetchone():
                    return provided_session_id
            except mysql.connector.Error:
                pass
            finally:
                cursor.close()
                connection.close()

    # 创建新会话ID
    return str(uuid.uuid4())


@router.post("/consult", response_model=None)
async def smart_consult(
    chat_request: ChatRequest,
    current_user: dict = Depends(get_current_user)
):
    """智能咨询（流式输出）- 仅依赖用户自然语言问题，自动解析商品意图"""
    ai_client = get_ai_client()
    user_id = current_user.get("user_id")

    # 获取或创建会话ID
    session_id = get_or_create_session_id(user_id, chat_request.session_id)

    # 保存用户消息
    save_chat_message(
        user_id=user_id,
        session_id=session_id,
        role="user",
        message_type="text",
        content=chat_request.question
    )

    # ⚠️ 不再使用 chat_request.good_id 或 good_name
    # 所有商品检索逻辑交由 LLM 客户端内部的 _parse_user_query 和条件查询完成
    product_info = None  # 显式设为 None，表示不传入具体商品

    # 流式返回AI响应并保存
    async def generate():
        full_response = ""
        try:
            async for chunk in ai_client.chat_with_retail_context(
                chat_request.question,
                product_info  # 始终为 None
            ):
                full_response += chunk
                yield chunk

            # 保存完整的AI回复
            save_chat_message(
                user_id=user_id,
                session_id=session_id,
                role="assistant",
                message_type="text",
                content=full_response,
                good_id=None  # 不再绑定具体商品ID
            )

        except Exception as e:
            error_msg = f"AI服务异常: {str(e)}"
            yield error_msg
            save_chat_message(
                user_id=user_id,
                session_id=session_id,
                role="assistant",
                message_type="text",
                content=error_msg
            )

    return StreamingResponse(
        generate(),
        media_type="text/plain",
        headers={"X-Session-ID": session_id}
    )


@router.post("/upload-image")
async def upload_image(
        file: UploadFile = File(...),
        session_id: str = None,
        current_user: dict = Depends(get_current_user)
):
    """上传图片并由AI识别商品 - 修复响应头版本"""
    # 验证文件类型
    allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
    if file.content_type not in allowed_types:
        raise HTTPException(
            status_code=400,
            detail="不支持的文件类型，仅支持 JPG、PNG、WebP 格式"
        )

    # 限制文件大小
    MAX_FILE_SIZE = 10 * 1024 * 1024

    user_id = current_user.get("user_id")

    # 获取或创建会话ID
    session_id = get_or_create_session_id(user_id, session_id)

    try:
        # 读取文件内容
        contents = await file.read()
        if len(contents) > MAX_FILE_SIZE:
            raise HTTPException(
                status_code=400,
                detail="文件大小超过10MB限制"
            )

        # 保存用户图片消息
        save_chat_message(
            user_id=user_id,
            session_id=session_id,
            role="user",
            message_type="image",
            content="[图片消息]",
            image_url=file.filename
        )

        # 初始化AI客户端
        ai_client = get_ai_client()

        # 创建流式响应
        async def generate_stream():
            full_response = ""
            try:
                # 调用AI识别图片并搜索商品
                async for chunk in ai_client.recognize_image_and_search(contents):
                    chunk_str = str(chunk) if not isinstance(chunk, str) else chunk
                    full_response += chunk_str
                    yield chunk_str

                # 保存完整的AI回复
                save_chat_message(
                    user_id=user_id,
                    session_id=session_id,
                    role="assistant",
                    message_type="text",
                    content=full_response
                )

            except Exception as e:
                error_msg = f"❌ 图片处理失败: {str(e)}"
                yield error_msg
                save_chat_message(
                    user_id=user_id,
                    session_id=session_id,
                    role="assistant",
                    message_type="text",
                    content=error_msg
                )

        return StreamingResponse(
            generate_stream(),
            media_type="text/plain; charset=utf-8",
            headers={
                "X-Session-ID": session_id,
                "Access-Control-Expose-Headers": "X-Session-ID"  # 重要：让前端能访问这个header
            }
        )

    except Exception as e:
        logging.error(f"图片上传处理错误: {e}")

        async def error_generator():
            yield f"❌ 图片处理失败: {str(e)}"

        return StreamingResponse(
            error_generator(),
            media_type="text/plain; charset=utf-8",
            headers={"X-Session-ID": session_id}
        )


@router.get("/history")
async def get_chat_history(
        session_id: str = None,
        limit: int = 50,
        current_user: dict = Depends(get_current_user)
):
    """获取用户聊天历史"""
    user_id = current_user.get("user_id")
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        if session_id:
            # 获取特定会话的历史记录
            cursor.execute("""
                SELECT id, session_id, role, message_type, content, image_url, 
                       good_id, created_at
                FROM chat_history
                WHERE user_id = %s AND session_id = %s
                ORDER BY created_at ASC
                LIMIT %s
            """, (user_id, session_id, limit))
        else:
            # 获取所有会话的最新记录
            cursor.execute("""
                SELECT ch1.* FROM chat_history ch1
                INNER JOIN (
                    SELECT session_id, MAX(created_at) as max_date
                    FROM chat_history
                    WHERE user_id = %s
                    GROUP BY session_id
                ) ch2 ON ch1.session_id = ch2.session_id AND ch1.created_at = ch2.max_date
                ORDER BY ch1.created_at DESC
                LIMIT %s
            """, (user_id, limit))

        history = cursor.fetchall()
        return {"history": history, "session_id": session_id}

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    finally:
        cursor.close()
        connection.close()


@router.get("/sessions")
async def get_user_sessions(
        current_user: dict = Depends(get_current_user)
):
    """获取用户的所有会话列表"""
    user_id = current_user.get("user_id")
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute("""
            SELECT session_id, MAX(created_at) as last_time, 
                   COUNT(*) as message_count
            FROM chat_history
            WHERE user_id = %s
            GROUP BY session_id
            ORDER BY last_time DESC
        """, (user_id,))

        sessions = cursor.fetchall()
        return {"sessions": sessions}

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    finally:
        cursor.close()
        connection.close()


@router.post("/sessions/new")
async def create_new_session(
        current_user: dict = Depends(get_current_user)
):
    """创建新的对话会话"""
    user_id = current_user.get("user_id")
    new_session_id = str(uuid.uuid4())

    # 可选：保存一个欢迎消息到新会话
    save_chat_message(
        user_id=user_id,
        session_id=new_session_id,
        role="assistant",
        message_type="text",
        content="👋 您好！我是智能零售助手，可以为您提供商品推荐、价格咨询、使用建议等服务。请问有什么可以帮您的？"
    )

    return {
        "session_id": new_session_id,
        "message": "新会话创建成功",
        "created_at": datetime.now().isoformat()
    }


@router.get("/sessions/{session_id}/messages")
async def get_session_messages(
        session_id: str,
        limit: int = 100,
        current_user: dict = Depends(get_current_user)
):
    """获取特定会话的所有消息"""
    user_id = current_user.get("user_id")
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute("""
            SELECT id, role, message_type, content, image_url, 
                   good_id, created_at
            FROM chat_history
            WHERE user_id = %s AND session_id = %s
            ORDER BY created_at ASC
            LIMIT %s
        """, (user_id, session_id, limit))

        messages = cursor.fetchall()

        # 验证会话是否存在
        if not messages:
            raise HTTPException(status_code=404, detail="会话不存在或无权访问")

        return {
            "session_id": session_id,
            "messages": messages,
            "total_count": len(messages)
        }

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    finally:
        cursor.close()
        connection.close()


@router.delete("/history/{session_id}")
async def delete_chat_history(
        session_id: str,
        current_user: dict = Depends(get_current_user)
):
    """删除特定会话的聊天记录"""
    user_id = current_user.get("user_id")
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor()
        cursor.execute("""
            DELETE FROM chat_history 
            WHERE user_id = %s AND session_id = %s
        """, (user_id, session_id))
        connection.commit()

        if cursor.rowcount == 0:
            raise HTTPException(status_code=404, detail="会话不存在或无权访问")

        return {"message": "聊天记录删除成功"}

    except mysql.connector.Error as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    finally:
        cursor.close()
        connection.close()


@router.delete("/history")
async def clear_all_chat_history(
        current_user: dict = Depends(get_current_user)
):
    """清空用户的所有聊天记录"""
    user_id = current_user.get("user_id")
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor()
        cursor.execute("""
            DELETE FROM chat_history 
            WHERE user_id = %s
        """, (user_id,))
        connection.commit()

        return {"message": "所有聊天记录已清空"}

    except mysql.connector.Error as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    finally:
        cursor.close()
        connection.close()


__all__ = [
    "router",
    "smart_consult",
    "upload_image",
    "get_chat_history",
    "get_user_sessions",
    "create_new_session",
    "get_session_messages",
    "delete_chat_history",
    "clear_all_chat_history",
]